import request from "@/utils/request.js";

export function wxAuthorize(_this) {
  const link = window.location.href;
  console.log(link);
  const openId = _this.$sessionStorage.get("openId");
  console.log(openId);
  // 已经授权登录过的就不用再授权了
  if (openId) return;

  // 如果拿到code，调用授权接口，没有拿到就跳转微信授权链接获取
  let code = getQueryString("code");
  if (code) {
    // 调用后台接口，授权
    request({
      url: "/weChat/getGZHOpenid",
      method: "post",
      data: { code: code }
    }).then(rsp => {
      console.log(rsp);
      if (rsp.code === 200 && rsp.data.code === code) {
        _this.$sessionStorage.set("openId", rsp.data.userInfoVO.wechatOpenid);
      } else {
        // code已经使用过了...
        if (rsp.content === "40163") {
          //重新获取code
          weChatAuthUrl(link);
        } else {
          _this.$toast.fail("授权错误,请刷新重试...");
        }
      }
    });
  } else {
    weChatAuthUrl(link);
  }
}

function weChatAuthUrl(link) {
  // 文科委的appid
  // let appid = 'wx7c6c2fe7010d6d01';

  // 大协会的appid
  let appid = "wx5b8ebbd4cbac6c69";
  let uri = encodeURIComponent(link);
  // let scope = 'snsapi_userinfo';
  let scope = "snsapi_base";
  let authURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=${scope}&state=123#wechat_redirect`;
  window.location.href = authURL;
}

function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}
